package io.babystar.modules.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.babystar.common.utils.PageUtils;
import io.babystar.common.utils.Query;
import io.babystar.common.utils.R;
import io.babystar.common.utils.ShiroUtils;
import io.babystar.modules.business.dao.CkInDao;
import io.babystar.modules.business.dao.CkOutDao;
import io.babystar.modules.business.dao.CkProductDao;
import io.babystar.modules.business.dao.ShopDao;
import io.babystar.modules.business.entity.CkInEntity;
import io.babystar.modules.business.entity.CkOutEntity;
import io.babystar.modules.business.entity.CkProductEntity;
import io.babystar.modules.business.entity.ShopEntity;
import io.babystar.modules.business.service.CkOutService;
import io.babystar.modules.business.service.CkProductService;
import io.babystar.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("ckOutService")
public class CkOutServiceImpl extends ServiceImpl<CkOutDao, CkOutEntity> implements CkOutService {

    @Autowired
    private CkProductDao ckProductDao;
    @Autowired
    private CkOutDao ckOutDao;
    @Autowired
    private CkInDao ckInDao;
    @Autowired
    private ShopDao shopDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String shopId = "";
        if(params.get("shopId")!=null){
            shopId = params.get("shopId").toString();
        }

        IPage<CkOutEntity> page = this.page(
                new Query<CkOutEntity>().getPage(params),
                new QueryWrapper<CkOutEntity>()
                        .eq(StringUtils.isNotBlank(shopId), "shop_id", shopId)
        );

        for(CkOutEntity ckOutEntity: page.getRecords()){
            CkProductEntity ckProductEntity = ckProductDao.selectById(ckOutEntity.getProductCode());
            if(ckProductEntity != null){
                ckOutEntity.setProductName(ckProductEntity.getProductName());
            }
            ShopEntity shopEntity = shopDao.selectById(ckOutEntity.getShopId());
            if(shopEntity!=null){
                ckOutEntity.setShopName(shopEntity.getShopName());
            }
            if(ckOutEntity.getShopId() !=null && ckOutEntity.getShopId().intValue() == -1){
                ckOutEntity.setShopName("总部");
            }
        }
        return new PageUtils(page);
    }

    @Override
    public PageUtils getByproductName(Map<String,Object> params){
        Integer count = ckOutDao.getByproductNameCount(params);
        Page<CkOutEntity> page = new Page<>();
        page.setTotal(count);
        Integer pageNuber = Integer.parseInt(params.get("page").toString());
        Integer pageSize = Integer.parseInt(params.get("limit").toString());
        page.setCurrent(pageNuber);
        page.setSize(pageSize);
        Long current = page.getCurrent();
        Long size = page.getSize();
        Long currentStart = size*current - size;
        params.put("currentStart",currentStart);
        params.put("size",size);
        page.setRecords(ckOutDao.getByproductName(params));
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public R delete(Integer id){
        SysUserEntity sysUser = ShiroUtils.getUserEntity();
        CkOutEntity ckOut = ckOutDao.selectById(id);
        CkProductEntity ckProductEntity = ckProductDao.selectById(ckOut.getProductCode());
        //判断是否存在该商品
        if(ckProductEntity.getNum() != null && !"".equals(ckProductEntity.getNum())){
            //修改商品数量
            Integer productNum = ckProductEntity.getNum() + ckOut.getOutNum();
            if(productNum.intValue()<0){
                return R.error("商量数量不足，回滚失败！");
            }
            ckProductEntity.setNum(productNum);
            ckProductEntity.setUpdateTime(new Date());
            ckProductEntity.setUpdator(sysUser.getUsername());
            //若更新成功再存入库单
            if(ckProductDao.updateById(ckProductEntity)>0){
                ckOutDao.deleteById(ckOut);
            }
        }else{
            return R.error("商品不存在！");
        }
        return R.ok("入库记录删除，数量回滚成功");
    }

    @Override
    @Transactional
    public R out(CkOutEntity ckOut) {
        CkProductEntity ckProductEntity = ckProductDao.selectById(ckOut.getProductCode());
        //判断是否存在该商品
        if (ckProductEntity.getNum() != null && !"".equals(ckProductEntity.getNum())) {
            //减少商品数量,库存不能减为负数
            if (ckOut.getOutNum() > ckProductEntity.getNum()) {
                return R.error(1, "库存不足");
            }
            Integer productNum = ckProductEntity.getNum() - ckOut.getOutNum();
            ckProductEntity.setNum(productNum);
            ckProductEntity.setUpdateTime(new Date());
            //减少总部库存
            if (ckProductDao.updateById(ckProductEntity) > 0) {
                ckOut.setCreateTime(new Date());
                ckOutDao.insert(ckOut);
                String ckoutType = ckOut.getCkOutType();
                // 给分公司铺货
                if ("1".equals(ckoutType)) {
                    // 铺货分公司ID
                    Integer outShopId = ckOut.getShopId();
                    Map<String, Object> shopProductParams = new HashMap<>();
                    shopProductParams.put("shop_id", outShopId);
                    shopProductParams.put("product_name", ckProductEntity.getProductName());
                    List<CkProductEntity> inProducts = ckProductDao.selectByMap(shopProductParams);
                    //分公司的商品存在，则直接入库；不存在先增加商品，再入库
                    if (inProducts != null && inProducts.size() > 0) {
                        CkProductEntity inProduct = inProducts.get(0);
                        //增加库存数量
                        Integer inNum = inProduct.getNum() + ckOut.getOutNum();
                        inProduct.setNum(inNum);
                        if (ckProductDao.updateById(inProduct) > 0) {
                            CkInEntity ckInEntity = new CkInEntity();
                            ckInEntity.setInNum(inNum);
                            ckInEntity.setProductCode(inProduct.getId() + "");
                            ckInEntity.setShopId(outShopId);
                            ckInEntity.setBusinessId(ckOut.getBusinessId());
                            ckInDao.insert(ckInEntity);
                        }
                    } else {
                        Integer inNum = ckOut.getOutNum();
                        //保存商品
                        ckProductEntity.setId(null);
                        ckProductEntity.setNum(inNum);
                        ckProductEntity.setShopId(outShopId);
                        ckProductEntity.setCreateTime(new Date());
                        ckProductDao.insert(ckProductEntity);
                        //增加库存
                        CkInEntity ckInEntity = new CkInEntity();
                        ckInEntity.setInNum(inNum);
                        ckInEntity.setProductCode(ckProductEntity.getId() + "");
                        ckInEntity.setShopId(outShopId);
                        ckInEntity.setBusinessId(ckOut.getBusinessId());
                        ckInDao.insert(ckInEntity);
                    }
                }
                return R.ok();
            } else {
                return R.error(1, "库存更新失败");
            }
        } else {
            return R.error(1, "该商品不存在");
        }
    }

    @Override
    public PageUtils queryCkOutCountList(Map<String, Object> params) {
        Page<CkOutEntity> page = new Page<>();
        Integer count = this.baseMapper.queryCkOutCountListCount(params);
        page.setTotal(count);
        Integer pageNuber = Integer.parseInt(params.get("page").toString());
        Integer pageSize = Integer.parseInt(params.get("limit").toString());
        page.setCurrent(pageNuber);
        page.setSize(pageSize);
        Long current = page.getCurrent();
        Long size = page.getSize();
        Long currentStart = size * current - size;
        params.put("currentStart", currentStart);
        params.put("size", size);
        page.setRecords(this.baseMapper.queryCkOutCountList(params));

        return new PageUtils(page);
    }
}